package com.vint.common;

import java.util.Random;

/*
 * 二叉树节点
 */
public class ListNode {
    public static int VAL_MAX = 10000;
    public static Random random = new Random();
    public int val;
    public ListNode next;
    public ListNode(int x) {
        val = x;
    }
    public static ListNode mockList(){
        boolean leaf = random.nextBoolean();
        ListNode root = null;
        if (leaf) {
            root = new ListNode(random.nextInt(VAL_MAX));
        }
        return root;
    }

    public static ListNode mockLoopList(){
        ListNode root = new ListNode(3);
        root.next = new ListNode(2);
        root.next.next = root;
        return root;
    }

    public static ListNode mockSpecific1(){
        ListNode root = new ListNode(3);
        root.next = new ListNode(2);
        return root;
    }

    /*
     * return lenght
     */
    public int getLenght(ListNode head) {
        ListNode visit = head;
        int lenght = 0;
        while (null != visit) {
            lenght++;
            visit = visit.next;
        }
        return lenght;
    }
    /*
     * return tail Node
     */
    public ListNode getTail(ListNode head) {
        ListNode visit = head;
        while (null != visit) {
            visit = visit.next;
        }
        return visit;
    }
    /*
     * return Nth Node
     */
    public ListNode getNth(ListNode head, int n) {
        ListNode visit = head;
        int length = 1;
        while (null != visit && length++ != n) {
            visit = visit.next;
        }
        return visit;
    }

    public ListNode copySelf(ListNode head) {
        if (null == head) {
            return null;
        }
        ListNode visit = new ListNode(head.val);
        ListNode newHead = visit;
        ListNode newVisit = head.next;
        while (null != newVisit) {
            visit.next = new ListNode(newHead.val);
            visit = visit.next;
            newVisit = newVisit.next;
        }
        return newHead;
    }
    public ListNode reverse(ListNode head) {
        if (null == head || null == head.next) {
            return head;
        }
        ListNode newHead = head;
        ListNode walk = head.next;
        newHead.next = null;
        while (null != walk) {
            ListNode nextWalk = walk.next;
            walk.next = newHead;
            newHead = walk;
            walk = nextWalk;
        }
        return newHead;
    }
}
